package com.ska.skautils.views;

import android.content.Context;
import android.transition.ChangeBounds;
import android.transition.Fade;
import android.transition.TransitionManager;
import android.transition.TransitionSet;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;

/**
 * ConstraintLayout 相关功能
 */
public class ConstraintLayoutUtils {
    private static ConstraintLayoutUtils instance;
    private Context mContext;
    private ConstraintLayout mConstraintLayout;
    private TransitionSet mCustomTransition; //transition动画
    private boolean isFrame1; //当前使用的是否是原始的布局
    private ConstraintSet constraintSet1 ; //保存frame_1中的布局参数
    private ConstraintSet constraintSet2 ; //保存frame_2中的布局参数

    private ConstraintLayoutUtils(ConstraintLayout constraintLayout,Context context) {
        mConstraintLayout =constraintLayout;
        mContext = context;
    }

    public static synchronized ConstraintLayoutUtils getInstance(ConstraintLayout constraintLayout, Context context) {
        if (instance == null) {
            instance = new ConstraintLayoutUtils(constraintLayout,context);
        }
        return instance;
    }

    /**
     * ConstraintLayoutUtils 带动效的 变换view
     * @param layoutId  变换后的 view
     */
    public  void  setReplaceView(int layoutId){
        isFrame1=true;
        constraintSet1 = new ConstraintSet(); //保存frame_1中的布局参数
        constraintSet2 = new ConstraintSet(); //保存frame_2中的布局参数
        mCustomTransition = new TransitionSet();
        mCustomTransition.addTransition(new Fade(Fade.IN))
                .addTransition(new ChangeBounds())
                .addTransition(new Fade(Fade.OUT));
        mCustomTransition.setOrdering(TransitionSet.ORDERING_TOGETHER);
        mCustomTransition.setDuration(500);
        //读取frame_1中的布局参数
        constraintSet1.clone(mConstraintLayout);
        //读取frame_2中的布局参数
        constraintSet2.clone(mContext,layoutId);
    }

    /**
     * 执行变换
     */
    public void switchViews(){
        //设置执行动画的ViewGroup以及transition

        TransitionManager.beginDelayedTransition(mConstraintLayout, mCustomTransition);
        if (isFrame1) {
            //将frame_2中的参数应用到当前的constaintlayout中
            constraintSet2.applyTo(mConstraintLayout);
            isFrame1 = false;

        } else {
            //将frame_1中的参数应用到当前的constaintlayout中
            constraintSet1.applyTo(mConstraintLayout);
            isFrame1 = true;
        }
    }

}